<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods/goodsList' }"
        >商品列表</el-breadcrumb-item
      >
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示信息区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="销售地区"></el-step>
        <el-step title="商品详情"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左侧的tab侧边栏 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="CommodityName">
              <el-input v-model="addForm.CommodityName"></el-input>
            </el-form-item>
            <el-row :gutter="30">
              <!-- 商品价格 -->
              <el-col :span="12">
                <el-form-item label="商品价格" prop="CommodityPrices">
                  <el-input v-model="addForm.CommodityPrices"></el-input>
                </el-form-item>
              </el-col>
              <!-- 商品库存 -->
              <el-col :span="12">
                <el-form-item label="商品库存" prop="CommodityStocks">
                  <el-input v-model="addForm.CommodityStocks"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="商品分类" prop="CommodityTypeId">
              <!-- 级联选择框 -->
              <el-cascader
                v-model="addForm.CommodityTypeId"
                :options="cateList"
                :props="{
                  expandTrigger: 'hover',
                  value: cateProps.value,
                  label: cateProps.label,
                  children: cateProps.children,
                }"
                @change="handleChange"
                clearable
                filterable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="店铺名称" prop="StoreName">
              <el-select
                v-model="addForm.FromStoreId"
                placeholder="请选择"
                filterable
                clearable
              >
                <el-option
                  v-for="item in storeList"
                  :key="item.id"
                  :label="item.storeName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <goods-add-params :goodsParams="this.addForm.CommodityTypeId" />
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="2">
            <goods-add-pics @commodity-images="handleCommodityImages" />
          </el-tab-pane>
          <el-tab-pane label="销售地区" name="3">
            <el-form-item label="可购买的城市" prop="CommodityAddress">
              <el-checkbox
                :indeterminate="isIndeterminate"
                v-model="checkAll"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <div style="margin: 15px 0"></div>
              <el-checkbox-group
                v-model="addForm.CommodityAddress"
                @change="handleCommodityAddressChange"
              >
                <el-checkbox v-for="city in cities" :label="city" :key="city">{{
                  city
                }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品详情" name="4">
            <!-- 富文本编辑器 -->
            <mavon-editor
              :ishljs="true"
              ref="md"
              @imgAdd="imgAdd"
              @imgDel="imgDel"
              v-model="addForm.CommodityDetails"
            />
            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="btnAdd" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 商品参数
import GoodsAddParams from './GoodsAddParams.vue'
// 商品图片
import GoodsAddPics from './GoodsAddPics.vue'
// 城市选择
const cityOptions = ['河北', '山西', '辽宁', '吉林', '黑龙江', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海', '台湾', '内蒙古', '广西', '西藏', '宁夏', '新疆', '北京', '天津', '上海', '重庆', '香港', '澳门'
]
export default {
  // 组件
  components: {
    // 商品参数
    GoodsAddParams,
    // 商品图片
    GoodsAddPics
  },
  data () {
    return {
      // 商品分类列表查询的参数
      queryInfo: {
        // 当前页码数
        pageIndex: 1,
        // 每页显示多少条数据
        pageSize: 5
      },
      // 激活的步骤条索引
      activeIndex: '0',
      // 添加
      addForm: {
        // 商品名称
        CommodityName: '',
        // 商品价格
        CommodityPrices: '',
        // 商品库存
        CommodityStocks: '',
        // 商品分类id
        CommodityTypeId: '',
        // 店铺id
        FromStoreId: '',
        // 商品图片id
        CommodityImagesId: [],
        // 商品详情
        CommodityDetails: '',
        // 销售城市
        CommodityAddress: ['河北', '山西', '辽宁', '吉林', '黑龙江', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海', '广西', '宁夏', '北京', '天津', '上海', '重庆'
        ]
      },
      // 左侧tab侧边栏验证规则对象
      addFormRules: {
        // 商品名称的验证规则
        CommodityName: [{ required: true, message: '商品名称不能为空！', trigger: 'blur' }],
        // 商品价格的验证规则
        CommodityPrices: [{ required: true, message: '商品价格不能为空！', trigger: 'blur' }],
        // 商品库存的验证规则
        CommodityStocks: [{ required: true, message: '商品库存不能为空！', trigger: 'blur' }],
        // 商品分类的验证规则
        CommodityTypeId: [{ required: true, message: '请选择商品分类！', trigger: 'blur' }],
        // 商品所属店铺的验证规则
        StoreName: [{ required: true, message: '请选择店铺名称！', trigger: 'blur' }]
      },
      // 商品分类列表
      cateList: [],
      // 店铺列表
      storeList: [],
      // 级联选择框属性绑定对象
      cateProps: {
        value: 'id',
        label: 'commodityTypeName',
        children: 'children'
      },
      // 全选框
      checkAll: false,
      // 所有的城市
      cities: cityOptions,
      // 设置 indeterminate 状态，只负责样式控制
      isIndeterminate: true
    }
  },
  created () {
    // 获取商品信息
    this.getGoodsInfo()
    // 获取商品分类列表
    this.getCateList()
    // 获取店铺列表
    this.getStoreList()
  },
  methods: {
    // 获取商品信息
    async getGoodsInfo () {
      const goodsId = this.$route.query.goodsId
      if (goodsId !== undefined) {
        // 说明用户点击的是编辑
        const { data: res } = await this.$http.get(`Commodities/id/${goodsId}`)
        if (res.meta.status !== 200) {
          // 商品信息获取失败
          this.$message.error('商品信息获取失败！')
        } else {
          // 商品信息获取成功
          this.addForm.CommodityName = res.data.commodities.commodityName
          this.addForm.CommodityPrices = res.data.commodities.commodityPrices
          this.addForm.CommodityStocks = res.data.commodities.commodityStocks
          this.addForm.CommodityTypeId = res.data.commodities.commodityTypeId.split(',').map(Number)
          this.addForm.FromStoreId = res.data.commodities.fromStoreId
          this.addForm.CommodityImagesId = res.data.commodities.commodityImagesId.split(',').map(Number)
          this.addForm.CommodityDetails = res.data.commodities.commodityDetails
          this.addForm.CommodityAddress = res.data.commodities.commodityAddress.split(',')
        }
      } else {
        // 说明用户点击的是添加
        console.log('添加');
      }
    },
    // 获取商品分类列表
    async getCateList () {
      // 往数据库中发送请求
      const { data: res } = await this.$http.get('commodityTypes', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        // 商品分类获取失败
        // 提示获取失败的信息
        this.$message.error('商品分类获取失败！')
      } else {
        // 获取二级分类
        for (let index = 0; index < res.data.commodityTypes.length; index++) {
          const { data: res2 } = await this.$http.get(`commodityTypes/Pid/${res.data.commodityTypes[index].id}`)
          res.data.commodityTypes[index].children = res2.data.commodityTypes
          // 获取三级分类
          for (let i = 0; i < res2.data.commodityTypes.length; i++) {
            const { data: res3 } = await this.$http.get(`commodityTypes/Pid/${res2.data.commodityTypes[i].id}`)
            res2.data.commodityTypes[i].children = res3.data.commodityTypes
          }
        }
        // 商品分类获取成功
        // 把商品分类数据列表赋值给 cateList
        this.cateList = res.data.commodityTypes
      }
    },
    // 获取店铺列表
    async getStoreList () {
      const { data: res } = await this.$http.get('Stores', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        // 获取店铺列表失败
        return this.$message.error('店铺列表获取失败！')
      } else {
        // 获取店铺列表成功
        // 将返回的数据中的Stores店铺列表赋值给StoreList
        this.storeList = res.data.stores
      }
    },
    // 处理级联选择框选中值的改变
    handleChange () {
      if (this.addForm.CommodityTypeId.length !== 3) {
        // 说明选中的不是三级分类
        this.addForm.CommodityTypeId = []
      }
    },
    // tab标签页离开之前触发的函数
    // activeName 为要前往的标签页
    // oldActiveName 为要离开的标签页
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && (this.addForm.CommodityName === '' || this.addForm.CommodityPrices === '' || this.addForm.CommodityStocks === '' || this.addForm.CommodityTypeId.length !== 3 || this.addForm.FromStoreId == 0)) {
        // 当前处于第一个标签页(基本信息)
        this.$message.error('请先完成基本信息！')
        // 阻止跳转
        return false
      }
    },
    // 删除图片
    async imgDel (pos) {
      delete this.img_file[pos]
      const str = pos[0]
      this.picForm.picPath = '/' + str.split('/')[3] + '/' + str.split('/')[4]
      const { data: res } = await this.$http.put('/article/deletepic', this.picForm)
    },
    // 将图片上传到服务器，返回地址替换到md中
    // 绑定@imgAdd event
    async imgAdd (pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      formdata.append('images', $file)
      const { data: res } = await this.$http.post('files/uploadFiles', formdata, { 'Content-Type': ' multipart/form-data' })
      var url = 'https://api.h1234.top/files/' + res.data[0].id
      this.$refs.md.$img2Url(pos, url)
    },
    // 处理子组件传过来的商品图片数组id
    handleCommodityImages (CommodityImagesId) {
      this.addForm.CommodityImagesId = CommodityImagesId
    },
    // 确认添加商品
    async add () {
      const editGoodsId = this.$route.query.goodsId
      if (editGoodsId) {
        // 编辑
        const { data: res } = await this.$http.put('Commodities/' + editGoodsId, {
          // 商品名称
          CommodityName: this.addForm.CommodityName,
          // 商品价格
          CommodityPrices: Number(this.addForm.CommodityPrices),
          // 商品库存
          CommodityStocks: Number(this.addForm.CommodityStocks),
          // 商品类型，转字符串格式传给后端
          CommodityTypeId: this.addForm.CommodityTypeId.toString(),
          // 店铺Id
          FromStoreId: Number(this.addForm.FromStoreId),
          // 商品图片数组，转字符串格式传给后端
          CommodityImagesId: this.addForm.CommodityImagesId.toString(),
          // 商品详情
          CommodityDetails: this.addForm.CommodityDetails,
          // 销售城市，转字符串格式传给后端
          CommodityAddress: this.addForm.CommodityAddress.toString()
        })
        if (res.meta.status !== 200) {
          // 编辑商品失败
          this.$message.error('编辑商品失败！')
        } else {
          // 编辑商品成功
          // 清空图片数组
          this.addForm.CommodityImagesId = []
          this.$message.success('编辑商品成功！')
          // 回到商品列表页，并刷新商品列表
          this.$router.push('/goods/goodsList')
        }
      } else {
        // 添加
        const { data: res } = await this.$http.post('Commodities', {
          // 商品名称
          CommodityName: this.addForm.CommodityName,
          // 商品价格
          CommodityPrices: Number(this.addForm.CommodityPrices),
          // 商品库存
          CommodityStocks: Number(this.addForm.CommodityStocks),
          // 商品类型，转字符串格式传给后端
          CommodityTypeId: this.addForm.CommodityTypeId.toString(),
          // 店铺Id
          FromStoreId: Number(this.addForm.FromStoreId),
          // 商品图片数组，转字符串格式传给后端
          CommodityImagesId: this.addForm.CommodityImagesId.toString(),
          // 商品详情
          CommodityDetails: this.addForm.CommodityDetails,
          // 销售城市
          CommodityAddress: this.addForm.CommodityAddress.toString()
        })
        if (res.meta.status !== 200) {
          // 商品增加失败
          this.$message.error('商品增加失败！')
        } else {
          // 商品增加成功
          // 清空图片数组
          this.addForm.CommodityImagesId = []
          this.$message.success('商品增加成功！')
          // 回到商品列表页，并刷新商品列表
          this.$router.push('/goods/goodsList')
        }
      }
    },
    // 可购买城市全选
    handleCheckAllChange (val) {
      this.addForm.CommodityAddress = val ? cityOptions : []
      this.isIndeterminate = false
    },
    // 复选框变化
    handleCommodityAddressChange (value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.cities.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length
    }
  }
}
</script>

<style lang="css" scoped>
/* 步骤条样式 */
.el-steps {
  margin: 15px;
  display: flex;
  justify-content: center;
}

/* 确认添加商品按钮 */
.btnAdd {
  margin-top: 10px;
}
</style>
